package com.yzc.config;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
//public class CorsFilter implements GlobalFilter, Ordered {
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//        HttpHeaders headers = response.getHeaders();
//
//        // 处理跨域请求的响应头
//        if (request.getHeaders().containsKey(HttpHeaders.ORIGIN)) {
//            String origin = request.getHeaders().getOrigin();
//            headers.add("Access-Control-Allow-Origin", origin); // 动态设置允许的 Origin
//            headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//            headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
//            headers.add("Access-Control-Max-Age", "3600"); // 预检请求缓存时间
//            headers.add("Access-Control-Allow-Credentials", "true"); // 允许携带凭证
//        }
//
//        // 如果是 OPTIONS 请求，直接返回 200 状态
//        if (request.getMethod() == HttpMethod.OPTIONS) {
//            response.setStatusCode(HttpStatus.OK);
//            return Mono.empty(); // 结束请求
//        }
//
//        // 继续链式过滤
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return -1; // 确保这个过滤器在其他过滤器之前执行
//    }
//}

